// ignore_for_file: avoid_print
import 'lib.dart';
import 'package:flutter/material.dart';

class Index extends StatefulWidget {
  const Index({super.key});

  @override
  State<Index> createState() => _IndexState();
}

class _IndexState extends State<Index> {
  Future<String> _getData() async {
    // 获取已实例化的对象
    var lib = Lib();
    // 日志的使用
    lib.log.debug('debug msg');
    lib.log.info('info msg');
    lib.log.warning('warning msg');
    lib.log.error('error msg', title: 'error title');
    // 永久数据的使用
    print(await lib.data.get('id'));
    print(await lib.data.set('id', 10));
    print(await lib.data.get('id'));
    print(await lib.data.set('id', null));

    // 运行时缓存的使用  => 全局变量
    print(lib.cache.get('id2'));
    lib.cache.set('id2', 20);
    print(lib.cache.get('id2'));
    var appdir = await lib.file.getAppdir();
    // 请求 get
    lib.request.ajax(
        url: "http://192.168.18.26:5000/",
        method: 'GET',
        success: (data) {
          lib.log.info(data.toString());
        },
        err: (data) {
          lib.log.error(data);
        });
    // 请求 post
    lib.request.ajax(
        url: "http://192.168.18.26:5000/",
        method: 'POST',
        data: {'id': '1', 'name': 'lisa'}, // 文件路径
        success: (data) {
          lib.log.info(data.toString());
        },
        err: (data) {
          lib.log.error(data);
        });
    // 请求 文件上传
    // 请求 文件下载
    // 下载
    lib.request.download(
        url: "http://192.168.18.26:5000/static/1.jpg",
        savePath: '${appdir}download/1.jpg',
        success: (data) {
          lib.log.info(data.toString());

          lib.request.ajax(
            url: 'http://192.168.18.26:5000/upload',
            method: 'POST',
            data: {'file': '${appdir}download/1.jpg'}, // 文件路径
            isUploadFile: true, // 标识这是一个文件上传请求
            success: (response) {
              lib.log.info('文件上传成功: $response');
            },
            err: (msg) {
              lib.log.info(msg.toString());
            },
          );
        },
        err: (data) {
          lib.log.error(data);
        },
        onReceiveProgress: (receivedBytes, totalBytes) {
          print(
              "下载进度: ${(receivedBytes / totalBytes * 100).toStringAsFixed(0)}%");
        });

    // 请求 404
    lib.request.ajax(
        url: "http://192.168.18.26:5000/404",
        method: 'POST',
        data: {
          'log': 'asd',
          'pwd': 'asd',
          'wp-submit': '登录',
          'redirect_to': 'http://0.0.0.0:8080/wp-admin/',
          'testcookie': '1',
        },
        success: (data) {
          lib.log.info(data.toString());
        },
        err: (data) {
          lib.log.error(data);
        });

    // 等待3秒
    await lib.sleep(3);

    // 创建目录
    String dirPath = 'example_dir/';
    bool created = await lib.file.createDir(dirPath);
    print('Directory created: $created');

    // 写入文件
    String filePath = '${dirPath}example.txt';
    bool written = await lib.file.writeFile(filePath, 'w', 'Hello, world!\n');
    print('File written: $written');

    // 写入文件
    written = await lib.file.writeFile(filePath, 'a', 'Hello, Lisa!\n');
    print('File written: $written');

    // 读取文件
    String content = await lib.file.readFile(filePath);
    print('File content: $content');

    // 复制文件
    String copyPath = '${dirPath}example_copy.txt';
    bool copied = await lib.file.copy(filePath, copyPath);
    print('File copied: $copied');

    // 移动
    String newDirPath = 'new_example_dir/';
    bool moved = await lib.file.move(dirPath, newDirPath);
    print('Directory moved: $moved');

    // 列出目录内容
    List dirContents = await lib.file.ls(newDirPath);
    var res = 'Directory contents:\n';
    for (var content in dirContents) {
      res += '${content['filename']} => ${content['size']}\n';
    }
    lib.log.info(res);
    // 检查文件或目录是否存在
    bool exists = await lib.file.exists(filePath);
    print('$filePath exists: $exists');
    var newFilePath = '${newDirPath}example.txt';
    // 获取文件大小
    int size = await lib.file.size(newFilePath);
    print('File size: $size bytes');

    // 获取文件的扩展名
    String extension = lib.file.extension(newFilePath);
    print('Extension: $extension');

    // 获取文件的基本名（不含扩展名）
    String basename = lib.file.basename(newFilePath);
    print('Basename: $basename');

    // 获取文件的目录名
    String dirname = lib.file.dirname(newFilePath);
    print('Dirname: $dirname');

    // 删除目录
    bool deleted = await lib.file.delDir(newDirPath);
    print('$newDirPath deleted: $deleted');
    return 'success';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<String>(
          future: _getData(), // 这里调用 _getData() 是合法的
          builder: (context, snapshot) {
            return Center(child: Text('首页 ${snapshot.data}'));
          }),
    );
  }
}
